import config from "@/config/app";
import store from "@/store";
const { HTTP_REQUEST_URL, HEADER, TOKENNAME } = config;

function toLogin() {
  store.commit("LOGOUT");
  uni.showToast({
    title: "请登录",
    icon: "none",
    duration: 1000,
  });
}
function base64ToUint8Array(base64String) {
  let padding = "=".repeat((4 - (base64String.length % 4)) % 4);
  let base64 = (base64String + padding).replace(/\-/g, "+").replace(/_/g, "/");
  let rawData = atob(base64);
  let outputArray = new Uint8Array(rawData.length);
  for (var i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}
function atob(input) {
  const chars =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  let str = input.replace(/=+$/, "");
  let output = "";
  if (str.length % 4 === 1) {
    throw new Error("InvalidLengthError");
  }
  for (let i = 0, len = str.length; i < len; i += 4) {
    const a = chars.indexOf(str.charAt(i));
    const b = chars.indexOf(str.charAt(i + 1));
    const c = chars.indexOf(str.charAt(i + 2));
    const d = chars.indexOf(str.charAt(i + 3));
    const sum = (a << 18) | (b << 12) | (c << 6) | d;
    output += String.fromCharCode(
      (sum >> 16) & 0xff,
      (sum >> 8) & 0xff,
      sum & 0xff
    );
  }

  return output;
}
/**
 * 发送请求
 */
function baseRequest(url, method, data, { noAuth = false, noVerify = false }) {
  let Url = HTTP_REQUEST_URL,
    header = HEADER;
  if (!noAuth) {
    //登录过期自动登录
  }

  if (store.state.token) header[TOKENNAME] = "Bearer " + store.state.token;
  if (store.state.uuid) header["uuid"] = store.state.uuid;
  return new Promise((reslove, reject) => {
    uni.request({
      url: Url + "/api/" + url,
      method: method || "GET",
      header: header,
      data: data || {},
      success: (res) => {
        // if (res.data.status == 400) {
        // 	uni.showToast({
        // 		title: res.data.message,
        // 		icon: 'none',
        // 		duration: 2000
        // 	});
        // }
        if (res.data && res.data.encode) {
          try {
            res.data = JSON.parse(res.data.data);
          } catch (e) {
            res.data = decodeURI(res.data.data);
          }
        }
        if (noVerify) reslove(res.data, res);
        else if (res.data.status == 200) reslove(res.data, res);
        else if (
          [410000, 410001, 410002, 40000].indexOf(res.data.status) !== -1
        ) {
          toLogin();
          reject(res.data);
        } else if (res.data.status == 501) {
          uni.reLaunch({
            url: "/pages/error/index",
          });
          reject(res.data);
        } else reject(res.data.message || "系统错误");
      },
      fail: (message) => {
        reject("请求失败");
      },
    });
  });
}
const request = {};
["options", "get", "post", "put", "head", "delete", "trace", "connect"].forEach(
  (method) => {
    request[method] = (api, data, opt) =>
      baseRequest(api, method, data, opt || {});
  }
);
export default request;
